import os
import shutil

default_work_path = os.getcwd()
out_apk = "build_apk"

PLATFORM_YY = 1
PLATFORM_YXF = 0


def build_platform(platform, debug=False, main_pack=True, input_channel=""):
    build_apk_path = "/Users/lzz/Desktop/project/yxf/orange"
    flavor = "Release"
    channel = "_yxf"

    if platform == PLATFORM_YY:
        build_apk_path = "/Users/lzz/Desktop/project/yiyuan/bt-app"
    if debug:
        flavor = "Staging"
    if not main_pack:
        channel = input_channel
    else:
        if platform == PLATFORM_YY:
            channel = "_yy"

    buildChanel = 'assemble%s%s' % (channel, flavor)
    build_apk(build_apk_path, buildChanel)


def build_apk(build_apk_path, build_chanel):
    if not os.path.exists(build_apk_path):
        print("项目不存在")
    if os.path.exists(out_apk):
        shutil.rmtree(out_apk)
    os.mkdir(out_apk)
    print("切换到打包项目目录：" + build_apk_path)
    os.chdir(build_apk_path)
    print(" *** build clean *** ：")
    _cmd("./gradlew clean")
    print(" **** 开始打包 **** ：")
    _cmd("./gradlew " + build_chanel)
    print(" **** 开始结束 **** ：")
    out_file = os.path.join("app", "build", "outputs", "apk")
    path_apk_real = []
    if os.path.exists(out_file):
        outList = os.listdir(out_file)
        for out in outList:
            channels = os.path.join(out_file, out)
            if os.path.exists(channels):
                channelList = os.listdir(channels)
                for out_channel in channelList:
                    flavors = os.path.join(channels, out_channel)
                    if os.path.exists(flavors):
                        flavorList = os.listdir(flavors)
                        for _flavor in flavorList:
                            if _flavor.endswith(".apk"):
                                path_apk_real.append(os.path.join(build_apk_path, flavors, _flavor))
    print("apk待拷贝路径：")
    print(path_apk_real)
    os.chdir(default_work_path)
    print("切换到打包项目目录：" + os.getcwd())
    for item in path_apk_real:
        print("src:" + item + ",dst:" + os.path.join(os.getcwd(), out_apk))
        shutil.copy(os.path.abspath(item), os.path.join(os.getcwd(), out_apk))


def _cmd(command):
    return print(os.popen(command).read())
